package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mec.beans.y2012.coreservlet.LongLivedCookie;

@WebServlet("/ClientAccessCountsServlet")
public class ClientAccessCountsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ClientAccessCountsServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String countString = CookieUtilities.getCookieValue(request, ACCESS_COUNT, ACESS_COUNT_INCREMENT.toString());
		int count = 1;
		try{
			count = Integer.parseInt(countString);
		}catch(NumberFormatException nfe){
			//
		}
		
		//
		LongLivedCookie c = new LongLivedCookie(ACCESS_COUNT, String.valueOf(count + 1));
		response.addCookie(c);
		//
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//
		String title = "Access Count Servlet";
		out.println(Constants.docType + ServletUtilities.headWithTitle(title) +
				"<body><h1>" + title + "</h1><h2>Ths is visit number: " + count + " by this browser.</h2>\n</body></html>"
				);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private static final String ACCESS_COUNT = "accessCount";
	private static final Integer ACESS_COUNT_INCREMENT = 1;
	private static final Logger logger = 
			Logger.getLogger(ClientAccessCountsServlet.class);
}
